import numpy as np
import matplotlib.pyplot as plt
def gates_case(n):      #n个门后的奖品情况
    gates = np.zeros(n)     #0表示山羊
    m = np.random.randint(0,n)
    gates[m] = 1        #在m号位置用1表示车
    return gates
def one_test(gates,t):     #t=1表示更换，t=0表示不更换
    num = len(gates)
    n = np.random.randint(0,num)
    if gates[n]==1:     #直接选到车
        if t==1:
            return 0
        elif t==0:
            return 1
        else:
            print("error,t should be 0 or 1")
    else:
        if t==0:
            return 0
        elif t==1:     #即没选到车，打算更换的情况
             m = np.random.randint(0, num - 2)       #在剩下有羊的门中选一个  
             k = -1
             for s in range(0, num):                 # 遍历所有门
                 if gates[s] == 0 and s!= n:            
                     k+=1                          
                 if k == m:                        
                     gates[s] = -1                #用-1表示门被打开
                     break
             m = np.random.randint(0, num - 2)    #重新选择
             k = -1
             for s in range(0,num):
                 if s!=n and gates[s]!=-1:     #不选之前的门和打开的门
                     k+=1
                 if k==m:
                     return gates[s]
        else:
            print("error,t should be 0 or 1")
def N_test(N,n,t):
    count=0
    for s in range(N):
        if one_test(gates_case(n),t):
            count+=1
    return count/N
#结果计算
for i in range(3,11):
    print(N_test(5000,i,1),end="  ")
    print(N_test(5000,i,0))
#可视化图1
n=5
cases=np.arange(10, 500)        
sr1=[N_test(i,n,1) for i in cases]
sr2=[N_test(i,n,0) for i in cases]
plt.plot(np.arange(10, 500), sr1, 'b.',label='change')
plt.plot(np.arange(10, 500), sr2, 'g.',label='not change')
plt.plot([10,500], [4/15, 4/15], 'r-')
plt.plot([10,500], [1/5, 1/5], 'r-')
plt.annotate('$y=1/5$',xy=(500,1/5),xytext=(+5,+30),textcoords='offset points',\
             fontsize=10,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.annotate('$y=8/15$',xy=(500,4/15),xytext=(+5,+30),textcoords='offset points',\
             fontsize=10,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.title('n=5')
plt.legend()
plt.grid(True)
plt.show()
#可视化图2
_cases=np.arange(3,11)
_sr1=[N_test(5000,i,1) for i in _cases]
_sr2=[N_test(5000,i,0) for i in _cases]
plt.plot(np.arange(3,11), _sr1, marker='o', mec='r', mfc='w',label='change')
plt.plot(np.arange(3,11), _sr2, marker='*', mec='r', mfc='g',label='not change')
plt.title('P-n')
plt.legend()
plt.grid(True)
plt.show()


